//
//  UserAccount.swift
//  WeiBo
//
//  Created by 陈贵 on 15/9/9.
//  Copyright © 2015年 hzj. All rights reserved.
//

/*
Optional({"access_token":"2.00QsRB9DPXBwAB7c5a0ce69f0VXxAd","remind_in":"157679999","expires_in":157679999,"uid":"3162442944"})
*/

import UIKit

class UserAccount: NSObject,NSCoding {

    
    var access_token:String?
    var remind_in:String?
    
    var expires_in:NSTimeInterval = 0{
        //当对expires_in赋值后便会调用didSet里的代码
        didSet{
            expitresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //过期日期
    var expitresDate:NSDate?
    var uid:String?
    var name:String?
    var avatar_large:String?
    
    init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    //使打印结果的描述信息可视化
    override var description:String{
        let key = ["access_token",  "remind_in","expires_in","uid","name","avatar_large","expitresDate"]
        return dictionaryWithValuesForKeys(key).description
    }
    
    //MARK: 用户账号的保存
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(expitresDate, forKey: "expitresDate")
        aCoder.encodeObject(name, forKey: "name")
    }
    //解档
    required init?(coder aDecoder: NSCoder) {
        uid = aDecoder.decodeObjectForKey("uid") as? String
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        expitresDate = aDecoder.decodeObjectForKey("expitresDate") as? NSDate
        name = aDecoder.decodeObjectForKey("name") as? String
    }
    //路径
    static let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask,true).last! as NSString).stringByAppendingPathComponent("account.list")
    
    //保存
    func saveTheUserAccount(){
        print(UserAccount.path)
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.path)
    }
    //读取
    class func loadTheUserAccount() ->UserAccount?{
        let userinfo = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount
        
        //OrderedAscending 升序
        if userinfo?.expitresDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending {
            return nil
        }
        return userinfo
    }

    
    
    
}
